package com.scorpio.api;


import com.alibaba.fastjson.JSONObject;
import com.scorpio.appuser.domain.AppUserEntity;
import com.scorpio.appuser.domain.UserShopCartEntity;
import com.scorpio.appuser.service.UserAddressService;
import com.scorpio.appuser.service.UserShopCartService;
import com.scorpio.appuser.vo.UpdateShopCartCheckVo;
import com.scorpio.appuser.vo.UpdateShopCartNumberVo;
import com.scorpio.appuser.vo.AddShopCartVo;
import com.scorpio.basic.vo.OperationIdVo;
import com.scorpio.basic.vo.OperationIdsVo;
import com.scorpio.common.exception.CustomException;
import com.scorpio.common.utils.ConvertUtils;
import com.scorpio.common.utils.StringUtils;
import com.scorpio.common.utils.treenode.TreeNodeUtil;
import com.scorpio.common.utils.verification.ValidatorUtils;
import com.scorpio.core.controller.BaseController;
import com.scorpio.core.domain.Result;
import com.scorpio.framework.annotation.Log;
import com.scorpio.framework.annotation.PersonalLogin;
import com.scorpio.framework.annotation.PersonalLoginUser;
import com.scorpio.goods.domain.GoodsCategoryEntity;
import com.scorpio.goods.domain.GoodsSpecEntity;
import com.scorpio.goods.dto.GoodsCategoryMiniDTO;
import com.scorpio.goods.service.GoodsCategoryService;
import com.scorpio.goods.service.GoodsService;
import com.scorpio.goods.service.GoodsSpecService;
import com.scorpio.goods.vo.FindSubmitShopInfoVo;
import com.scorpio.goods.vo.GoodsNumberVo;
import com.scorpio.goods.vo.GoodsVo;
import com.scorpio.order.service.OrderService;
import com.scorpio.order.vo.SubmitShopCartOrderVo;
import com.scorpio.order.vo.SubmitShopOrderVo;
import com.scorpio.redis.cachelock.RedisLockException;
import com.scorpio.redis.constant.AppConfigConstant;
import com.scorpio.system.service.ISysConfigService;
import com.scorpio.utils.AppUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/goods")
public class GoodsController extends BaseController {

    @Autowired
    private GoodsCategoryService categoryService;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private GoodsSpecService specService;

    @Autowired
    private UserShopCartService shopCartService;

    @Autowired
    private UserAddressService addressService;

    @Autowired
    private ISysConfigService sysConfigService;

    @Log(title = "商品分组分类")
    @GetMapping("category")
    public Result category() {
        String versions = sysConfigService.selectConfigByKey(AppConfigConstant.CONFIG_MINI_APP_VERSIONS);
        String mversions = AppUtils.getUserDeviceInfo().getVersions();
        List<GoodsCategoryEntity> list;
        if (!StringUtils.isEmpty(versions) && !StringUtils.isEmpty(mversions) && !versions.equals(AppUtils.getUserDeviceInfo().getVersions())) {
            list = categoryService.appList(14l);
        } else {
            list = categoryService.appList(null);
        }
        list = TreeNodeUtil.bulid(list, 0l, 2);
        return Result.success(list);
    }

    @Log(title = "商品分组分类-小程序组件分组")
    @GetMapping("category_mini")
    public Result category_mini() {
        List<GoodsCategoryEntity> list = categoryService.appList(null);
        List<GoodsCategoryMiniDTO> miniList = new ArrayList<>();
        for (GoodsCategoryEntity entity : list) {
            GoodsCategoryMiniDTO dto = ConvertUtils.sourceToTarget(entity, GoodsCategoryMiniDTO.class);
            dto.setText(entity.getName());
            miniList.add(dto);
        }
        miniList = TreeNodeUtil.bulid(miniList, 0l, 2);
        GoodsCategoryMiniDTO item = new GoodsCategoryMiniDTO();
        item.setText("全部");

        List<GoodsCategoryMiniDTO> children = new ArrayList<>();
        GoodsCategoryMiniDTO item2 = new GoodsCategoryMiniDTO();
        item2.setText("全部");
        children.add(item2);

        item.setChildren(children);
        miniList.add(0, item);
        return Result.success(miniList);
    }

    @Log(title = "商品列表")
    @GetMapping("goodsList")
    public Result goodsList(GoodsVo vo) {
        return Result.success(goodsService.goodsList(vo));
    }

    @Log(title = "商品")
    @GetMapping("goodsDetails")
    public Result goodsDetails(@Validated OperationIdVo vo) {
        return Result.success(goodsService.details(vo.getId()));
    }

    @Log(title = "商品SKU查询")
    @GetMapping("skuList")
    public Result skuList(@Validated OperationIdVo vo) {
        return Result.success(goodsService.skuList(vo.getId()));
    }

    @Log(title = "商品详情")
    @GetMapping("goodsSpec")
    public Result goodsSpec(@Validated GoodsNumberVo vo) {
        return Result.success(specService.selectByNumber(vo.getNumber()));
    }

    @PersonalLogin
    @Log(title = "获取提交商品信息")
    @PostMapping("findSubmitShopInfo")
    public Result findSubmitShopInfo(@PersonalLoginUser AppUserEntity user, @RequestBody FindSubmitShopInfoVo vo) {
        if (vo.getGoods() == null && (vo.getCarts() == null || vo.getCarts().length == 0)) {
            throw new CustomException("无效购买商品");
        }
        List<GoodsSpecEntity> goods;
        float totalPeice = 0;
        if (vo.getGoods() != null) {
            ValidatorUtils.validateEntity(vo.getGoods());
            if (vo.getGoods().getAmountTotal() == null || vo.getGoods().getAmountTotal() <= 0) {
                throw new CustomException("无效的购买数量");
            }
            goods = specService.findSubmitShopInfo(Arrays.asList(vo.getGoods()));
        } else {
            List<UserShopCartEntity> carts = shopCartService.selectBysUser(user.getId(), vo.getCarts());
            if (carts.size() != vo.getCarts().length) {
                throw new CustomException("提交出错");
            }
            List<GoodsNumberVo> voList = new ArrayList<>();
            for (UserShopCartEntity cart : carts) {
                GoodsNumberVo numberVo = new GoodsNumberVo();
                numberVo.setNumber(cart.getSpecNumber());
                numberVo.setAmountTotal(cart.getAmountTotal());
                if (numberVo.getAmountTotal() == null || numberVo.getAmountTotal() <= 0) {
                    throw new CustomException("无效的购买数量");
                }
                voList.add(numberVo);
            }
            goods = specService.findSubmitShopInfo(voList);
        }
        for (GoodsSpecEntity entity : goods) {
            totalPeice += entity.getPresentPrice() * entity.getAmountTotal();
        }
        JSONObject json = new JSONObject();
        json.put("totalPeice", totalPeice);
        json.put("orderList", goods);
        json.put("address", addressService.selectRecommendAddress(user.getId()));
        return Result.success(json);
    }

    @Log(title = "添加购物车")
    @PostMapping("addShopCart")
    @PersonalLogin
    public Result addShopCart(@PersonalLoginUser AppUserEntity user, @Validated @RequestBody AddShopCartVo vo) {
        vo.uid = user.getId();
        return toResult(shopCartService.addShopCart(vo));
    }

    @Log(title = "更新购物车数量")
    @PostMapping("updateShopCartNumber")
    @PersonalLogin
    public Result updateShopCartNumber(@PersonalLoginUser AppUserEntity user, @Validated @RequestBody UpdateShopCartNumberVo vo) {
        vo.uid = user.getId();
        return toResult(shopCartService.updateShopCartNumber(vo));
    }

    @Log(title = "更新购物车选中")
    @PostMapping("updateShopCartCheck")
    @PersonalLogin
    public Result updateShopCartCheck(@PersonalLoginUser AppUserEntity user, @Validated @RequestBody UpdateShopCartCheckVo vo) {
        vo.uid = user.getId();
        return toResult(shopCartService.updateShopCartCheck(vo));
    }

    @Log(title = "删除购物车上")
    @PostMapping("deleteShopCart")
    @PersonalLogin
    public Result deleteShopCart(@PersonalLoginUser AppUserEntity user, @Validated @RequestBody OperationIdsVo vo) {
        return toResult(shopCartService.deleteShopCart(user.getId(), vo.getIds()));
    }

    @Log(title = "清空购物车")
    @PostMapping("clearShopCart")
    @PersonalLogin
    public Result clearShopCart(@PersonalLoginUser AppUserEntity user) {
        return toResult(shopCartService.clearShopCart(user.getId()));
    }

    @Log(title = "购物车列表")
    @GetMapping("cartList")
    @PersonalLogin
    public Result cartList(@PersonalLoginUser AppUserEntity user) {
        return Result.success(shopCartService.appList(user.getId()));
    }

    @Log(title = "购物车商品总数")
    @GetMapping("shopCartTotal")
    @PersonalLogin
    public Result shopCartTotal(@PersonalLoginUser AppUserEntity user) {
        return Result.success(shopCartService.shopCartTotal(user.getId()));
    }


}
